﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Data.OracleClient;
using System.Configuration;
using UFC.Common;
using UFC.DBUtility;


namespace AutoCheck
{
    class Send_Check
    {

        public void RunContainerSync()
        {
            try
            {
                DataTable mydt = GetContaienr();
                if (mydt == null)
                {
                    LogHelp.WriteLog("没有可处理的批次");
                }
                Dictionary<string, string> strList;
                CheckTo.TCMTOMESservice   sap = new  CheckTo.TCMTOMESservice ();

                foreach (DataRow dr in mydt.Rows)
                {
                    LogHelp.WriteLog("处理批次开始" + dr["containername"].ToString());
                    strList = new Dictionary<string, string>();

                    string[] strArray = dr["containername"].ToString().Split('/');

                    strList.Add("LJH", dr["productname"].ToString());//零件号
                    strList.Add("LJMC", dr["description"].ToString());//零件名称
                    strList.Add("KKR", dr["fullname"].ToString());//开卡人

                    strList.Add("PCH", dr["containername"].ToString().Replace(dr["productname"].ToString(), ""));//批次号

                    strList.Add("KKSL", dr["qty"].ToString());//开卡数量
                    strList.Add("CLPH", dr["MaterialTrademark"].ToString());//材料牌号
                    strList.Add("CLGG", dr["MaterialSpecification"].ToString());//材料规格
                    strList.Add("CNO", dr["containerid"].ToString()); //批次ID

                    string strXML = CreateXMLForContainer(strList);
                    LogHelp.WriteLog(strXML); 
                    string resXML=  sap.DNC_Send_PrepareStatus_Service(strXML);

                    string strMsg = "";

                    if (GetERPRcvXML(strMsg))
               {
                   OracleDAL.InsertSyncRecord(dr["ncarrangementsid"].ToString(), m_cRecordType, "成功", 0);
                   //成功后更新为已推送
                   string updateSql = string.Format("UPDATE ncarrangements SET isintegration=1 WHERE ncarrangementsid='{0}'", dr["ncarrangementsid"]);
                   OracleHelper.ExecuteSql(updateSql);
               }
               else
                        OracleDAL.InsertSyncRecord(dr["ncarrangementsid"].ToString(), m_cRecordType, strMsg, 0);

                }
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("批次提交", myError);
            }
        }
   
        /// <summary>
        /// 批次获取
        /// </summary>
        /// <returns></returns>
        private DataTable GetContaienr()
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.AppendLine("select pb.productname,p.description,e.fullname, c.containername,c.qty,p.MaterialTrademark ,p.MaterialSpecification ");
                strSql.AppendLine(" ,c.containerid from Container c ");
                strSql.AppendLine(" left join product p on p.productid = c.productid  ");
                strSql.AppendLine(" left join productbase pb on pb.productbaseid = p.productbaseid ");
                strSql.AppendLine(" left join starthistorydetail shd on shd.containerid=c.containerid ");
                strSql.AppendLine(" left join employee e on e.employeeid=shd.startemployeeid ");
                strSql.AppendLine(" left join movehistory m on m.historyid = c.containerid and m.pathid is not null");
                strSql.AppendLine(" left join workflowstep wfs on wfs.workflowstepid=m.stepid");
                strSql.AppendLine(" left join workflow wf on wf.workflowid = wfs.workflowid");
                strSql.AppendLine(" left join mfgorder mo on mo.mfgorderid = c.mfgorderid");
                strSql.AppendLine(" left join workflowbase wfb on wfb.workflowbaseid = wf.workflowbaseid");
                strSql.AppendLine(" left join WriteToERPRecord werpr on werpr.recordid=c.containerid and werpr.recordtype='container'");
                strSql.AppendFormat(" where mo.mfgorderid is not null and m.qty>0 and    werpr.recordid is  null and c.factorystartdate>to_date('{0}','yyyy-MM-dd HH24:mi:ss')", ConfigurationManager.AppSettings["ContainerDate"]);
                strSql.AppendLine(" and wfb.workflowname='MW' and wf.workflowrevision='1' and wfs.sequence>1 ");
                DataSet myDS = OracleHelper.Query(strSql.ToString());
                if (myDS == null)
                    return null;
                if (myDS.Tables.Count == 0)
                    return null;
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("批次获取", e);
                return null;
            }
        }
        /// <summary>
        /// 生产批次XML
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        private string CreateXMLForContainer(Dictionary<string, string> strList)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
                XmlNode ReqNode = doc.CreateElement("ReqMsg");
                XmlNode headerNode = doc.CreateElement("header");
                XmlNode senderNode = doc.CreateElement("sendSysName");
                senderNode.InnerText = "APP_MES";
                XmlNode rcvNode = doc.CreateElement("rcvSysName");
                rcvNode.InnerText = "APP_ERP";
                XmlNode extNode = doc.CreateElement("extConfig");
                extNode.AppendChild(doc.CreateElement("isReTry"));
                extNode.LastChild.InnerText = "false";
                extNode.AppendChild(doc.CreateElement("FunName"));
                extNode.LastChild.InnerText = "ZPPF_CREATE_BATCH_FROMEMS";
                headerNode.AppendChild(senderNode);
                headerNode.AppendChild(rcvNode);
                headerNode.AppendChild(extNode);
                ReqNode.AppendChild(headerNode);
                XmlNode documentNode = doc.CreateElement("document");
                string strData = "<BATCHINFO><BATCH>";
                foreach (KeyValuePair<string, string> _key in strList)
                {
                    strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
                }
                strData += "</BATCH></BATCHINFO>";
                documentNode.AppendChild(doc.CreateCDataSection(strData));
                ReqNode.AppendChild(documentNode);
                doc.AppendChild(ReqNode);
                return doc.InnerXml;
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产批次XML", e);
                return string.Empty;
            }
        }
        /// <summary>
        /// 获取ERP反馈XML
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetERPRcvXML(string strXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

            if (isSuccess == "true" || meaasge =="S")
            {
                return true;
            }
            else
            {
                LogHelp.WriteLog(meaasge);
                return false;
            }
        }

   
        private const string m_cRecordType = "container";
    }

    }
